package com.qipay.utils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class LocalCache {
    // private static final long SECOND_TIME = 1000;//默认过期时间 20秒
    // private static final int DEFUALT_VALIDITY_TIME = 20;//默认过期时间 20秒
    private static final Timer timer;
    private static final ConcurrentHashMap<String, Object> map;
    static {
        timer = new Timer();
        map = new ConcurrentHashMap<String, Object>();
    }

    /**
     * 增加缓存对象
     *
     * @param key
     * @param ce
     * @param validityTime
     */
    public static void setCache(String key, Object ce, int validityTime) {
        map.put(key, new CacheWrapper(validityTime, ce));
        timer.schedule(new TimeoutTimerTask(key), validityTime * 1000);
    }

    // 获取缓存KEY列表
    public static Set<String> getCacheKeys() {
        return map.keySet();
    }

    public static List<String> getKeysFuzz(String patton) {
        List<String> list = new ArrayList<String>();
        for (String tmpKey : map.keySet()) {
            if (tmpKey.contains(patton)) {
                list.add(tmpKey);
            }
        }
        if (isNullOrEmpty(list)) {
            return null;
        }
        return list;
    }

    public static Integer getKeySizeFuzz(String patton) {
        Integer num = 0;
        for (String tmpKey : map.keySet()) {
            if (tmpKey.startsWith(patton)) {
                num++;
            }
        }
        return num;
    }

    /**
     * 增加缓存对象
     *
     * @param key
     * @param ce
     *            有效时间
     */
    public static void setCache(String key, Object ce) {
        map.put(key, new CacheWrapper(ce));
    }

    /**
     * 获取缓存对象
     *
     * @param key
     * @return
     */
    public static <T> T getCache(String key) {
        CacheWrapper wrapper = (CacheWrapper) map.get(key);
        if (wrapper == null) {
            return null;
        }
        return (T) wrapper.getValue();
    }

    /**
     * 检查是否含有制定key的缓冲
     *
     * @param key
     * @return
     */
    public static boolean contains(String key) {
        return map.containsKey(key);
    }

    /**
     * 删除缓存
     *
     * @param key
     */
    public static void delCache(String key) {
        map.remove(key);
    }

    /**
     * 删除缓存
     *
     * @param key
     */
    public static void delCacheFuzz(String key) {
        for (String tmpKey : map.keySet()) {
            if (tmpKey.contains(key)) {
                map.remove(tmpKey);
            }
        }
    }

    /**
     * 获取缓存大小

     */
    public static int getCacheSize() {
        return map.size();
    }

    /**
     * 清除全部缓存
     */
    public static void clearCache() {
        map.clear();
    }

    /**
     * @projName：lottery
     * @className：TimeoutTimerTask
     * @description：清除超时缓存定时服务类
     * @creater：Coody
     * @creatTime：2014年5月7日上午9:34:39
     * @alter：Coody
     * @alterTime：2014年5月7日 上午9:34:39 @remark：
     * @version
     */
    static class TimeoutTimerTask extends TimerTask {
        private String ceKey;

        public TimeoutTimerTask(String key) {
            this.ceKey = key;
        }

        @Override
        public void run() {
            CacheWrapper cacheWrapper = (CacheWrapper) map.get(ceKey);
            if (cacheWrapper == null || cacheWrapper.getDate() == null) {
                return;
            }
            if (new Date().getTime() < cacheWrapper.getDate().getTime()) {
                return;
            }
            LocalCache.delCache(ceKey);
        }
    }

    public static boolean isNullOrEmpty(Object obj) {
        try {
            if (obj == null)
                return true;
            if (obj instanceof CharSequence) {
                return ((CharSequence) obj).length() == 0;
            }
            if (obj instanceof Collection) {
                return ((Collection<?>) obj).isEmpty();
            }
            if (obj instanceof Map) {
                return ((Map<?, ?>) obj).isEmpty();
            }
            if (obj instanceof Object[]) {
                Object[] object = (Object[]) obj;
                if (object.length == 0) {
                    return true;
                }
                boolean empty = true;
                for (int i = 0; i < object.length; i++) {
                    if (!isNullOrEmpty(object[i])) {
                        empty = false;
                        break;
                    }
                }
                return empty;
            }
            return false;
        } catch (Exception e) {
            return true;
        }

    }

    private static class CacheWrapper {
        private Date date;
        private Object value;

        public CacheWrapper(int time, Object value) {
            this.date = new Date(System.currentTimeMillis() + time * 1000);
            this.value = value;
        }

        public CacheWrapper(Object value) {
            this.value = value;
        }

        public Date getDate() {
            return date;
        }

        public Object getValue() {
            return value;
        }
    }
}
